package com.vol.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vol.JwtHelper;
import com.vol.MD5Util;
import com.vol.RedisUtils;
import com.vol.dao.SysRoleauthDao;
import com.vol.entity.Result;
import com.vol.dao.SysUserDao;
import com.vol.entity.SysMenu;
import com.vol.entity.SysRoleauth;
import com.vol.entity.SysUser;
import com.vol.mapper.SysMenuMapper;
import com.vol.mapper.SysRoleauthMapper;
import com.vol.model.Sys_Actions;
import com.vol.requestparams.LoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LoginService {
    @Autowired
    private RedisUtils<Object> redisUtils;
    @Autowired
    private RedisUtils<List<String>> redisUtilsAuth;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysRoleauthMapper sysRoleauthMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private JwtHelper jwtHelper;

    @Autowired
    private MD5Util md5Util;

    public Result login(LoginParams loginParams) throws JsonProcessingException {
        String yzm = redisUtils.getKey("LoginResult") + "";
        System.out.println(yzm + "=============" + loginParams.verificationCode);
        if (!loginParams.verificationCode.trim().equals(yzm.trim())) {
            return Result.build(null, 308, "验证码输入错误!", false);
        }

        String username = loginParams.getUserName();
        String password = loginParams.getPassword();
        //用户登录验证步骤
        //第一步：根据username查询该用户，返回用户实体
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, username);
        List<SysUser> listUser = sysUserDao.list(lambdaQueryWrapper);
        if (listUser.size() > 0) {
            SysUser user = listUser.get(0);
            //第二步：比对用户实体密码于前端加密的密码是否一致
            String webUserPass = md5Util.encrypt(password);
            String dbUserPass = user.getSbpwd();
            if (webUserPass.equals(dbUserPass)) {
                //第三步：存储用户权限，存储到redis中
                List<String> listAuth = new ArrayList<>();
                //管理员权限
                if (user.getRoleId() == 1) {
                    List<SysMenu> listmenu = sysMenuMapper.selectList(null);
                    for (SysMenu menu : listmenu) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        Sys_Actions[] Actions = objectMapper.readValue(menu.getAuth(), Sys_Actions[].class);
                        for (Sys_Actions act : Actions) {
                            listAuth.add(menu.getUrl() + ":" + act.getValue());
                        }
                    }
                } else {//普通用户权限
                    List<SysRoleauth> list = sysRoleauthMapper.selectAllAuth(user.getRoleId());
                    for (SysRoleauth sysRoleauth : list) {
                        String Url = sysRoleauth.getUrl();
                        String AuthValue = sysRoleauth.getAuthvalue();
                        List<String> listAuthValue = Arrays.asList(AuthValue.split(","));
                        for (String auth : listAuthValue) {
                            listAuth.add(Url + ":" + auth);
                        }
                    }
                }
                redisUtilsAuth.setKey("listAuth" + user.getUserId(), listAuth);

                //第四步：生成token、并提示登录成功！
                Map map = new HashMap();
                map.put("token", jwtHelper.createToken(Long.valueOf(user.getUserId())));
                map.put("userName", user.getUsername());
                map.put("img", null);
                return Result.ok(map, 310, "登录成功!");
            } else {
                return Result.build(null, 308, "密码输入错误!", false);
            }
        } else {
            return Result.build(null, 308, "用户名不存在!", false);
        }
        //return Result.build(null,308,"用户名或密码错误!",false);

    }


}
